#include "SysTick.h"

/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
  
__IO uint32_t TimingDelay=0;

void SysTick_Init(void)
{
  /*  更新主频数值 ↓  */
  uint32_t ahbprediv, pllprediv, pllmul, mainclk;
  
  switch (RCC->MAINCLKSRC)
  {
    case 0x00:  /* MHSI used as main clock */
      mainclk = MHSI_VALUE;
      break;
    case 0x01:  /* FHSI used as main clock */
      mainclk = FHSI_VALUE;
      break;
    case 0x03:  /* HSE used as main clock */
      mainclk = HSE_VALUE;
      break;
    case 0x02:  /* PLL used as main clock */
      pllprediv = (((RCC->PLLPRE & ((0xf<<1) | 0x01)) + 1) >> 1) + 1;  
      pllmul = (0x03 - ((ANCTL->PLLCR >> 6) & 0x03)) * 4 + 12;
    
      if (RCC->PLLSRC & 0x01)
      {
        mainclk = 8000000 * pllmul / pllprediv;
      }
      else
      {
        mainclk = 8000000 * pllmul / pllprediv;
      }
      break;
    default:
      mainclk = 48000000;
      break;
  }
  
  ahbprediv = (((RCC->AHBPRE & ((0xf<<1) | 0x01)) + 1) >> 1) + 1;  

  SystemCoreClock = mainclk / ahbprediv;

  
  /*  systick参数配置  */
  
  SysTick->LOAD  = (uint32_t)((SystemCoreClock/8/1000000) - 1UL);                         /* set reload register */
  
  SCB->SHP[11] = 0;/* set Priority for Systick Interrupt */

  
 // NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */
  SysTick->VAL   = 0UL;                                             /* Load the SysTick Counter Value */
  SysTick->CTRL  &=~(1<<2);  //配置为外部时钟源
  SysTick->CTRL  = (1<<1) |         1;                         /* Enable SysTick IRQ and SysTick Timer */                                                   /* Function successful */
}

void delay_us(__IO uint32_t nTime)
{ 
  TimingDelay = nTime;

  while(TimingDelay != 0);
}

void delay_ms(__IO uint32_t nTime)
{ 
  while(nTime)
  {
    delay_us(1000);
    nTime--;
  }
}
/**
  * @brief  This function handles SysTick Handler.
  * @param  None
  * @return None
  */
void SysTick_Handler(void)
{
  if (TimingDelay != 0x00)
  { 
    TimingDelay--;
  }
}

